import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { backstage } from './backstage'
import { mapbox } from './mapbox'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    component: () => import('../views/Home.vue'),
  },
  {
    path: '/eharth',
    component: () => import('../assets/eharth.vue'),
  },
  {
    path: '/dataScreen',
    component: () => import('../views/dataScreen/index.vue'),
    meta: { requiresCamera: true, title: '大屏' },
  },
  {
    path: '/dataScreen/three',
    component: () => import('../views/dataScreen/three/index.vue'),
    meta: { requiresCamera: true, title: 'three' },
  },
  {
    path: '/dataScreen/oasisEngine',
    component: () => import('../views/dataScreen/oasisEngine/index.vue'),
    meta: { requiresCamera: true, title: 'oasisEngine' },
  },
  {
    path: '/dataScreen/three/dome/dome1',
    component: () => import('../views/dataScreen/three/dome/dome1.vue'),
    meta: { requiresCamera: true, title: 'dome1' },
  },
  {
    path: '/dataScreen/three/dome/tank',
    component: () => import('../views/dataScreen/three/dome/tank.vue'),
    meta: { requiresCamera: true, title: '坦克' },
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/backstage/login.vue'),
    meta: { requiresCamera: true, title: '登入' },
  },
  {
    path: '/arithmetic',
    name: 'arithmetic',
    component: () => import('../views/arithmetic/index.vue'),
    meta: { requiresCamera: true, title: '递增的三元子序列' },
  },

  backstage,
  ...mapbox,
]

export const router = createRouter({
  // 4. 内部提供了 history 模式的实现。为了简单起见，我们在这里使用 hash 模式。
  history: createWebHashHistory(),
  routes, // `routes: routes` 的缩写
})

router.beforeEach((to, from, next) => {
  // ...
  console.log('路由前置守护')
  console.log(router.getRoutes())

  if (to.meta.title) {
    document.title = to.meta.title
  }

  if (to.meta.verification) {
    const token = localStorage.getItem('token')
    if (!token) {
      router.push({ name: 'login' })
    }
  }
  // 返回 false 以取消导航
  next()
})

router.beforeResolve(async to => {
  if (to.meta.requiresCamera) {
    try {
      // await askForCameraPermission()
      console.log(123)
    } catch (error) {
      console.log(error)

      // if (error instanceof NotAllowedError) {
      //   // ... 处理错误，然后取消导航
      //   return false
      // } else {
      //   // 意料之外的错误，取消导航并把错误传给全局处理器
      //   throw error
      // }
    }
  }
})
